package com.superme.gateway.filter;


import com.superme.gateway.config.WebWhitelist;
import com.superme.gateway.exception.LoginException;
import com.superme.gateway.utils.IpUtil;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;

/**
 * 登录过滤器
 * 作者: yanruizhi
 * 时间: 2023/8/17 14:15
 */
@Getter
@Component
@Slf4j
public class AuthFilter implements GlobalFilter {
    @Resource
    private Jedis jedis;
    @Resource
    private WebWhitelist webWhitelist;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //网关拦截
        ServerHttpRequest request = exchange.getRequest();
        String string = request.getPath().toString();
        //记录ip
        IpUtil.logIpAddress(request);
        //不在白名单内
        log.info("请求路径: {}", string);
        if (!webWhitelist.getWhitelist().contains(string)) {
            //进行登录认证
            String token = request.getHeaders().getFirst("token");
            if (token == null || token.isEmpty()) {
                throw new LoginException("请先登录");
            }
            Boolean exists = jedis.exists(token);
            if (!exists) {
                throw new LoginException("登录信息已过期,请重新登录");
            }
        }
        return chain.filter(exchange);

    }

}
